package com.study.kafkademo.kafka.custom;

import com.alibaba.fastjson.JSONObject;
import com.study.kafkademo.kafka.custom.model.KafkaMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;

@Component
@Slf4j
public class CustomKafkaProducer {

    private final KafkaTemplate<String, String> kafkaTemplate;

    public CustomKafkaProducer(KafkaTemplate<String, String> kafkaTemplate) {
        this.kafkaTemplate = kafkaTemplate;
    }

    //自定义 主题 topic
    public static final String TOPIC_TEST = "topic.test.custom";

    public static final String TOPIC_GROUP1 = "topic.group1.custom";

    public static final String TOPIC_GROUP2 = "topic.group2.custom";


    public void sendMessge(String topicTest, KafkaMessage message) {
        final ListenableFuture<SendResult<String, String>> send = kafkaTemplate.send(topicTest, JSONObject.toJSONString(message));
        
        send.addCallback(new ListenableFutureCallback<SendResult<String, String>>() {
            @Override
            public void onFailure(Throwable ex) {
                //发送消息失败
                log.error(TOPIC_TEST + "-生成者 发送消息失败：" + ex.getMessage());
            }

            @Override
            public void onSuccess(SendResult<String, String> result) {
                //发送消息成功
                log.info(TOPIC_TEST + "-生成者 发送消息成功：" + JSONObject.toJSONString(result));
            }
        });

    }
}
